package com.medsoft.drpcp.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import static com.medsoft.drpcp.meta.DrpcpHeadConstant.DRPCP_MSG_ID_OFFSET;
import static com.medsoft.drpcp.meta.DrpcpHeadConstant.DRPCP_MSG_ID_LEN;
import static com.medsoft.drpcp.meta.DrpcpHeadConstant.DRPCP_MSG_BODY_OFFSET;
import static com.medsoft.drpcp.meta.DrpcpMetaConstant.HEARTBEAT_MSG;
import static com.medsoft.drpcp.meta.DrpcpHeadConstant.DRPCP_CRC32_OFFSET;
import static com.medsoft.drpcp.meta.DrpcpHeadConstant.DRPCP_CRC32_LEN;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.medsoft.base.utils.CRCUtils;
import com.medsoft.drpcp.DrpcpRouter;
import com.medsoft.drpcp.exception.DrpcpException;
import com.medsoft.drpcp.meta.DrpcpHeadConstant;

public class DrpcpClientBusiHandler extends SimpleChannelInboundHandler<Object> {

	static final Logger logger = LoggerFactory.getLogger(DrpcpClientBusiHandler.class);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		logger.debug(msg.toString());
		if(msg.toString().substring(0, HEARTBEAT_MSG.length()).equals(HEARTBEAT_MSG)) {
			DrpcpRouter.drpcpMultiplex.get(HEARTBEAT_MSG).put(msg.toString());
		} else {
			if(Long.parseLong(msg.toString().substring(DRPCP_CRC32_OFFSET,DRPCP_CRC32_OFFSET + DRPCP_CRC32_LEN)) == CRCUtils.getCRC32Value(msg.toString().substring(DRPCP_MSG_BODY_OFFSET))) {
				DrpcpRouter.drpcpMultiplex.get(msg.toString().substring(DRPCP_MSG_ID_OFFSET,DRPCP_MSG_ID_OFFSET + DRPCP_MSG_ID_LEN)).put(msg.toString().substring(DRPCP_MSG_BODY_OFFSET));
				return;
			} else {
				throw new DrpcpException(DrpcpHeadConstant.ERROR_INFO_CRC32_CHECK_FAIL);
			}
		}
	}
}
